package com.kongjs.application.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.kongjs.application.service.CodeService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class CodeServiceImpl implements CodeService {
    private static final QrConfig config = new QrConfig();

    static {
        // 高纠错级别
        config.setErrorCorrection(ErrorCorrectionLevel.H);
    }

    //@Value("${qcode.url}")
    //private String qcodeUrl;

    /*
     * 签名url二维码
     * */
    @Override
    public String qcode() {
        long ms = System.currentTimeMillis();
        String url = "?timestamp=" + ms ;
        Sign sign = SecureUtil.sign(SignAlgorithm.SHA256withRSA);
        String signedHex = sign.signHex(url);
        String signUrl = url + "&sign=" + signedHex;
        FastByteArrayOutputStream outputStream = new FastByteArrayOutputStream();
        QrCodeUtil.generate(signUrl, config, "png", outputStream);
        return "data:image/png;base64," + Base64.encode(outputStream.toByteArray());
    }
}
